// Globals

try
{
  netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
}
catch (ex)
{
  alert("This theme requires you to set some permissions\nfor the options panel to work properly.\n\nBrowse to 'about:config' in your address bar and set\n'signed.applets.codebase_principal_support' to true\nif you need those options or just ignore this message if not.");
}

const emid="{d650973c-0444-4ac7-9d00-19e3613c83b9}";

var userChromeText;
var cleanUserChromeText;
var emptyUserChromeText;

var presentSubSkins = "";

var commentCount = 0;
var commentIndex = new Array();
var commentSize  = new Array();

var subSkinA = new Array();
subSkinA[subSkinA.length] = "bigaddons";
subSkinA[subSkinA.length] = "colorfulbars";
subSkinA[subSkinA.length] = "darktabbar";
subSkinA[subSkinA.length] = "fixthrobber";
subSkinA[subSkinA.length] = "hidebarbuttons";
subSkinA[subSkinA.length] = "nocolor";
subSkinA[subSkinA.length] = "slimbookmarks";
subSkinA[subSkinA.length] = "slimtabbar";
subSkinA[subSkinA.length] = "verttabbar";

function loadFile()
{
  netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");

  var fileName = 'userChrome.css';
  var targetNodeID = 'editChrome';
  var label = 'path-chrome';
  var chromeDir = getChromeDir(fileName);
  var fName = fileName;
  var size;

  userChromeText = '';

  var fileLocal = Components.classes["@mozilla.org/file/local;1"]
                  .createInstance(Components.interfaces.nsILocalFile);
  fileLocal.initWithPath(chromeDir);
  fileLocal.append(fName);

  var is = Components.classes["@mozilla.org/network/file-input-stream;1"]
           .createInstance(Components.interfaces.nsIFileInputStream);
  var sis = Components.classes["@mozilla.org/scriptableinputstream;1"]
            .createInstance(Components.interfaces.nsIScriptableInputStream);

  userChromeText = '';

  if (fileLocal.exists())
  {
    is.init(fileLocal,0x01, 00004, null);
    sis.init(is);
    size = sis.available();
    userChromeText = sis.read(sis.available());
  }
  else if (/css$/i.test(fName)) // && ! f.exists()
  {
    fName = fName.replace('.css', '-example.css');

    fileLocal.initWithPath(chromeDir);
    fileLocal.append(fName);

    if (fileLocal.exists())
    {
      is.init( fileLocal,0x01, 00004, null);
      sis.init( is );
      size = sis.available();
      userChromeText = sis.read(sis.available());
    }
    else
    {
      var extDefaultsDir = getExtDefaultsPath();
      if (extDefaultsDir.length > 0)
      {
        fileLocal.initWithPath(extDefaultsDir);
        fileLocal.append(fName);
        if (fileLocal.exists())
        {
          is.init(fileLocal,0x01, 00004, null);
          sis.init(is);
          size = sis.available();
          userChromeText = sis.read(sis.available());
        }
      }
    }
  }
  else
  {
      alert('Problem creating userChrome.css!');
      return;
  }

  if (userChromeText.length == 0)
  {
    userChromeText = '@namespace url("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul");\r\n';
  }

  cleanup();

  for (var i = 0; i < subSkinA.length; i++)
  {
    var sS = subSkinA[i];
    var re = new RegExp('@import\\s+url\\s*\\(\\s*"chrome://browser/skin/subskins/'+sS+'.css"\\s*\\)\\s*;');
    if (re.test(cleanUserChromeText))
    {
      document.getElementById(sS).checked = true;
      presentSubSkins += '|' + sS;
    }
    else
    {
      document.getElementById(sS).checked = false;
    }
  }

  if (presentSubSkins.length > 0)
  {
    presentSubSkins = '('+presentSubSkins.replace(/\|/,'')+')';
    var re = new RegExp('@import\\s+url\\s*\\(\\s*"chrome://browser/skin/subskins/'
             + presentSubSkins + '.css"\\s*\\)\\s*;\\s*', 'g');
    emptyUserChromeText = userChromeText.replace(re,'');
  }
  else
  {
    emptyUserChromeText = userChromeText;
  }

  return null;
}


function cleanup()
{
  cleanUserChromeText = "";
  var state = 0;

  for (var i=0; i < userChromeText.length; i++)
  {
    var c = userChromeText.charAt(i);

    switch (state)
    {
      case 0:
        if (c == '/') {state = 1; break;}
        if (c == '"') {state = 4; cleanUserChromeText += c;
                                  break;}
        if (c == "'") {state = 5; cleanUserChromeText += c;
                                  break;}
                      {           cleanUserChromeText += c;
                                  break;}
      case 1:
        if (c == '/') {state = 1; cleanUserChromeText += '/';
                                  break;}
        if (c == '*') {state = 2; commentIndex[commentCount] = i-1;
                                  commentSize[commentCount] = 2;
                                  commentCount++;
                                  cleanUserChromeText += '  ';
                                  break;}
                      {state = 0; cleanUserChromeText += '/' + c;
                                  break;}
      case 2:
        commentSize[commentCount-1]++;
        if (c == '*') {state = 3; break;}
                      {           break;}
      case 3:
        commentSize[commentCount-1]++;
        if (c == '/') {state = 0; break;}
        if (c == '*') {state = 3; break;}
                      {state = 2; break;}
      case 4:
        if (c == '"') {state = 0; cleanUserChromeText += c; break;}
                      {           cleanUserChromeText += c; break;}
      case 5:
        if (c == "'") {state = 0; cleanUserChromeText += c; break;}
                      {           cleanUserChromeText += c; break;}
    }
  }

  if (state == 1) {cleanUserChromeText += '/';}
  {
  	return null;
  }
}


function empty()
{
  var re = new RegExp('@import\\s+url\\s*\\(\\s*"chrome://browser/skin/subskins/'+presentSubSkins+'.css"\\s*\\)\\s*;\\s*', 'g');
  emptyUserChromeText = userChromeText.replace(re,'');
}


function emptyOLD()
{
  var tail = cleanUserChromeText;
  var re = new RegExp('@import\\s+url\\s*\\(\\s*"chrome://browser/skin/subskins/'+presentSubSkins+'.css"\\s*\\)\\s*;');
  var covered = 0;
  var skip = 0;
  var mtch = '';
  var commentNumber=0;
  emptyUserChromeText = '';

  while (re.test(tail))
  {
    var r_exec = re.exec(tail);
    var mtch = r_exec[0];
    emptyUserChromeText += tail.substr(0,r_exec.index);

    while ((commentNumber < commentCount) && (commentIndex[commentNumber] < emptyUserChromeText.length + skip))
    {
      emptyUserChromeText = emptyUserChromeText.substr(0, commentIndex[commentNumber] - skip)
                            + userChromeText.substr(commentIndex[commentNumber],commentSize[commentNumber])
                            + emptyUserChromeText.substr(commentIndex[commentNumber] + 2 - skip);
      commentNumber++;
    }

    r2_exec = /\s*$/.exec(emptyUserChromeText);

    if (r2_exec[0].length > 0)
    {
      emptyUserChromeText = emptyUserChromeText.substr(0,r2_exec.index);
      skip += r2_exec[0].length;
    }

    tail = tail.substr(r_exec.index+mtch.length);
    skip += mtch.length;
  }

  emptyUserChromeText += tail;

  while ((commentNumber < commentCount) && (commentIndex[commentNumber] < emptyUserChromeText.length + skip))
  {
    emptyUserChromeText = emptyUserChromeText.substr(0, commentIndex[commentNumber] - skip)
                          + userChromeText.substr(commentIndex[commentNumber],commentSize[commentNumber])
                          + emptyUserChromeText.substr(commentIndex[commentNumber] + 2 - skip);
    commentNumber++;
  }
}

function saveChanges()
{
  netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");

  var newUserChromeText = emptyUserChromeText;

  for (var i = 0; i < subSkinA.length; i++)
  {
    var sS = subSkinA[i];
    if (document.getElementById(sS).checked)
    {
      newUserChromeText = '@import url("chrome://browser/skin/subskins/'+sS+'.css");\r\n' + newUserChromeText;
    }
  }

  var fileName = "userChrome.css";
  var data = newUserChromeText;

  var chromeDir = getChromeDir(fileName);
  var fName = fileName;

  try
  {
    var fileLocal = Components.classes["@mozilla.org/file/local;1"]
                             .createInstance(Components.interfaces.nsILocalFile);
    fileLocal.initWithPath(chromeDir);
    fileLocal.append(fName);
    var outputStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
        .createInstance(Components.interfaces.nsIFileOutputStream);
    outputStream.init(fileLocal, 0x04 | 0x08 | 0x20, 420, 0);
    var result = outputStream.write(data, data.length);
    outputStream.close();
    fixUserContent();
    alert("Restart Firefox to activate changes!");
  }
  catch (ex)
  {
    alert("Restart Firefox to activate changes!");
  }
}


function getChromeDir(fileName)
{
  netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");

  var p;
  var NSIFILE = Components.interfaces.nsIFile;
  var dirLocator = Components.classes["@mozilla.org/file/directory_service;1"]
                   .getService(Components.interfaces.nsIProperties);
  var p = dirLocator.get("UChrm", NSIFILE).path;
  if (! /css$/i.test(fileName))
  {
    p = dirLocator.get("ProfD", NSIFILE).path;
  }

  return p;
}

function getExtDefaultsPath()
{
  netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");

  var p;
  var NSIFILE = Components.interfaces.nsIFile;
  var dirLocator = Components.classes["@mozilla.org/file/directory_service;1"]
                   .getService(Components.interfaces.nsIProperties);
  var p = dirLocator.get("ProfD", NSIFILE).path;
  var dirLocal = Components.classes["@mozilla.org/file/local;1"]
                 .createInstance(Components.interfaces.nsILocalFile);
  dirLocal.initWithPath(p);
  dirLocal.append("extensions");
  dirLocal.append(emid);
  dirLocal.append("chrome");
  dirLocal.append("chrome.jar!");

  if (dirLocal.exists() && dirLocal.isDirectory()) // Fx and Tb
  {
    return dirLocal.path;
  }
  else // seamonkey
  {
    p = dirLocator.get("ProfDefNoLoc", NSIFILE).path;
    dirLocal.initWithPath(p);
    dirLocal.append("chrome");
    if (dirLocal.exists() && dirLocal.isDirectory())
    {
      return dirLocal.path;
    }
  }
  return '';
}


function fixUserContent()
{
  netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");

  var fileName = 'userContent.css';
  var chromeDir = getChromeDir(fileName);
  var fName = fileName;
  var size;

  var fileLocal = Components.classes["@mozilla.org/file/local;1"]
                           .createInstance(Components.interfaces.nsILocalFile);
  fileLocal.initWithPath(chromeDir);
  fileLocal.append(fName);

  var is = Components.classes["@mozilla.org/network/file-input-stream;1"]
           .createInstance( Components.interfaces.nsIFileInputStream );
  var sis = Components.classes["@mozilla.org/scriptableinputstream;1"]
            .createInstance( Components.interfaces.nsIScriptableInputStream );

  var userContentText = '';

  if (fileLocal.exists())
  {
    is.init( fileLocal,0x01, 00004, null);
    sis.init( is );
    size = sis.available();
    userContentText = sis.read( sis.available() );
  }
  else if (/css$/i.test(fName)) // && ! f.exists()
  {
    fName = fName.replace('.css', '-example.css');

    fileLocal.initWithPath(chromeDir);
    fileLocal.append(fName);

    if (fileLocal.exists())
    {
      is.init( fileLocal,0x01, 00004, null);
      sis.init( is );
      size = sis.available();
      userContentText = sis.read( sis.available() );
    }
    else
    {
      var extDefaultsDir = getExtDefaultsPath();
      if (extDefaultsDir.length > 0)
      {
        fileLocal.initWithPath(extDefaultsDir);
        fileLocal.append(fName);
        if (fileLocal.exists())
        {
          is.init( fileLocal,0x01, 00004, null);
          sis.init( is );
          size = sis.available();
          userContentText = sis.read( sis.available() );
        }
      }
    }
  }
  else
  {
    // Problem Here Quit All
  }

  if (userContentText.length == 0)
      userContentText = '@namespace url("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul");\r\n';

  var subSkin = 'macscrollbar';
  var re = new RegExp('@import\\s+url\\s*\\(\\s*"chrome://browser/skin/subskins/'
                        + subSkin + '.css"\\s*\\)\\s*;\\s*', 'g');
  var newUserContentText = userContentText.replace(re,'');

  if (document.getElementById(subSkin).checked)
  {
    newUserContentText = '@import url("chrome://browser/skin/subskins/'+subSkin+'.css");\r\n' + newUserContentText;
  }

  if (newUserContentText != userContentText)
  {
    var data = newUserContentText;

    try
    {
      fName = fileName;
      var fileLocal = Components.classes["@mozilla.org/file/local;1"]
                               .createInstance(Components.interfaces.nsILocalFile);
      fileLocal.initWithPath(chromeDir);
      fileLocal.append(fName);
      var outputStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
          .createInstance( Components.interfaces.nsIFileOutputStream );
      outputStream.init( fileLocal, 0x04 | 0x08 | 0x20, 420, 0 );
      var result = outputStream.write( data, data.length );
      outputStream.close();
    }
    catch (ex)
    {
      alert('Problem saving ' + fName);
    }
  }

  return null;
}

function openURL(aURL)
{
  if (window.opener)
  {
    window.opener.openURL(aURL);
  }
  else
  {
    openDialog("chrome://browser/content/browser.xul", "_blank", "chrome,all,dialog=no", aURL, null, null);
  }
}
